<?php
namespace Home\Controller;
use Think\Controller;
/*
 ×类目管理控制器
 ×
 */
class TypeController extends HomeController {
	/*
	 * 类目列表
	 */
	static public $treeList = array();

	public function index(){
		//获取分类树
		$tree=getListCat();
		$this->assign('tree',$tree);
		$this->display();
	
	}
	public function addType(){
		$tree=getListCat();
		$this->assign('tree',$tree);
		//获取规格
		$specids=M('spec')->getField('specid',true);
		$speval=M('spec a')->join(' inner join '.C('DB_PREFIX').'specval b on a.specid=b.specid')
		                   ->getField('b.specvalid,a.name as spename,a.memo, a.specid, b.name as val');
		 $specrow=array();
		 foreach($specids as $k=>$val){
		 	foreach($speval as $key=>&$value){
		 		if($val==$value['specid']){
		 			$specrow[$value['specid']]['name']=$value['spename'];
		 			$specrow[$value['specid']]['memo']=$value['memo'];
		 			$specrow[$value['specid']]['val'].=$value['val'].'&nbsp;,&nbsp;';
		 			unset($value);
		 		}
		 	}
		 }
		 //获取所有品牌
		$brands=M('brand')->getField('brandid,brandname');
		$this->assign('brands',$brands);
        $this->assign('specrow',$specrow);
		$this->display();
	}
	/*
	 *编辑分类
	 *@param typeid
	 *
	 */
	public function editType()
	{
		$where['typeid']=I('get.typeid','','strip_tags');
		//获取类目基本信息
		$type=M('type');
		$typeinfo=$type->where($where)->select();
        //获取分类树
        $catelist=getListCat();
		//获取类目对应的扩展属性
		$type_property=M('type_property');
		$property=$type_property->where($where)->select();
		//获取所有品牌
		$brands=M('brand')->getField('brandid,brandname');
		//获取类目对应的品牌
		$typebrand=M('type_brand')->where($where)->getField('brandid,typeid');
        $newbrand=array();
        foreach($brands as $key=>$value)
        {
        	foreach($typebrand as $k=>$v)
        	{
        		if($k==$key)
        		{
        			
        			$newbrand[$key]['checked']=1;
        		}else
        		{
        			$newbrand[$key]['brandname']=$value;
        		}
        	}
        }

		//获取类目对应的规格
		$type_spec=M('type_spec');
		$specs=$type_spec->where($where)->getField('specid,typeid');
		//获取所有规格
		$specids=M('spec')->getField('specid',true);
		$speval=M('spec a')->join(' inner join '.C('DB_PREFIX').'specval b on a.specid=b.specid')
		                   ->getField('b.specvalid,a.name as spename,a.memo, a.specid, b.name as val');
		 $specrow=array();
		 foreach($specids as $k=>$val){
		 	foreach($speval as $key=>&$value){
		 		if($val==$value['specid']){
		 			$specrow[$value['specid']]['name']=$value['spename'];
		 			$specrow[$value['specid']]['memo']=$value['memo'];
		 			$specrow[$value['specid']]['val'].=$value['val'].'&nbsp;,&nbsp;';
		 			unset($value);
		 		}
		 	}
		 }

		 foreach($specrow as $key=>&$value)
		 {
              foreach($specs as $k=>$v)
              {
              		if($k==$key)
              		{
              			$value['checked']=1;
              		}
              		
              }

		 }
		 //var_dump($catelist);die;
		$this->assign('typeid',$where['typeid']);
		$this->assign('brands',$newbrand);
		$this->assign('specrow',$specrow);
		$this->assign('tree',$catelist);
		$this->assign('propertys',$property);
		$this->assign('typeinfo',$typeinfo[0]);
		$this->display('edittype');

	}
	/*
	 * 更新类目
	 */
	public function updateType(){	
		$data['pid']=I('post.typeid','','strip_tags');
		$typeid=I('post.tid','','strip_tags');
		$data['typename']=I('post.name','','strip_tags');
		$temp['propertyname']=I('post.propertynames','','strip_tags');

	    $temp['selvals']=I('post.selvals','','strip_tags');//属性值
	    $specids=I('post.specids','','strip_tags');//规格值
		//调用上传图片
	 
	 if(!empty($_FILES['listimg']['tmp_name'])){
	 	$data['imgpath']=$this->uploadimg();

	    if ($data['imgpath']==false)
	     {
	     	$this->error('图片尺寸不符');
	     	//echo  "<script type='text/javascript'>alert('图片尺寸不符');window.history.go(-1);</script>";die;
	     }
	 }
		//更新基本信息
		$type=M('type');
		$result=$type->where('typeid=%d',$typeid)->save($data);

		//追加的属性及属性值
	        if(!empty($temp['propertyname']))
	        {
	        	foreach($temp['propertyname'] as $key=>$value)
	        	{
	          		$datalist[]=array('typeid'=>$typeid,'propertyname'=>$value,'selval'=>$temp['selvals'][$key]);
	        	}
		        $type_property=M('type_property');
		        $type_propertyvalue=M('type_propertyvalue');
		        $type_property->startTrans();
		        $pro_selval=array();
		        foreach($datalist as $k=>$v)
		        {
		        	$propertyid=$type_property->data($v)->add();
		        	$pro_selval[]=array('propertyid'=>$propertyid,'typeid'=>$v['typeid'],'selstring'=>$v['selval']);
		        }
	       		 $temp=array();
		        foreach($pro_selval as $key=>$value)
		        {
		        	$selarr=explode(',', $value['selstring']);
		        	foreach($selarr as $k=>$v)
		        	{
		        		$sel_list[]=array('typeid'=>$value['typeid'],'propertyid'=>$value['propertyid'],'propertyvalue'=>$v);
		        	}
		        }
		        //var_dump($sel_list);die;
	       		$valueid=$type_propertyvalue->addAll($sel_list);
	       		//将属性值插入数据库
	       		//echo M()->getLastSql();die;
		       if($propertyid && $valueid)
		       {
		       		$type_property->commit(); // 插入属性和属性值成功则提交
		       		
		       }else{
		       		$type->rollback();//不成功则回滚
		       }

	        }
		//追加类目对应的规格	    
	    $type_spec=M('type_spec');
	   // $oldspcids= $type_spec->where('typeid=%d',$typeid)->getField('specid',true);
	   
		if(!empty($specids))
	     {
	     	$type_spec_list=array();
		     foreach($specids as $key=>$value)
		     {
		     	$type_spec_list[]=array('typeid'=>$typeid,'specid'=>$value);
		     }
	     	//批量添加 类目——规格
	     	$specid=M('type_spec')->addAll($type_spec_list);
	     }

	      echo "<script type='text/javascript'>alert('修改成功'); window.history.go(-1);</script>";

	
	}

	public function deleType(){
		echo '删除类目';
	}
	public function saveType(){
		return false;die;
		$data['typename']=I('post.name','','strip_tags');
		$data['pid']=$_POST['typeid'];
		$temp['propertyname']=I('post.propertynames','','strip_tags');
		$temp['selvals']=I('post.selvals','','strip_tags');
		$specids=I('post.specid','','strip_tags');
		$brands=I('post.brands','','strip_tags');
		$type=M('type');
		$config['path']=C('Admin_IMG_PATH');
		$config['maxsize']=C('IMG_MAX_SIZE');
		$img=imgUpload($config);
		$imginfo=$img['typeimg'];
		if(!empty($imginfo['savename']))
		{
			$data['imgpath']=C('Admin_IMG_PATH').$imginfo['savepath'].$imginfo['savename'];
		}
		$typeid=$type->add($data); //添加类目

        //保存 type_property 类目 属性
        if(!empty($temp['propertyname']))
        {
        	foreach($temp['propertyname'] as $key=>$value)
        	{
          		$datalist[]=array('typeid'=>$typeid,'propertyname'=>$value,'selval'=>$temp['selvals'][$key]);
        	}
	        $type_property=M('type_property');
	        $type_propertyvalue=M('type_propertyvalue');
	        $type_property->startTrans();
	        $pro_selval=array();
	        foreach($datalist as $k=>$v)
	        {
	        	$propertyid=$type_property->data($v)->add();
	        	$pro_selval[]=array('propertyid'=>$propertyid,'typeid'=>$v['typeid'],'selstring'=>$v['selval']);
	        }
       		 $temp=array();
	        foreach($pro_selval as $key=>$value)
	        {
	        	$selarr=explode(',', $value['selstring']);
	        	foreach($selarr as $k=>$v)
	        	{
	        		$sel_list[]=array('typeid'=>$value['typeid'],'propertyid'=>$value['propertyid'],'propertyvalue'=>$v);
	        	}
	        }
       		$valueid=$type_propertyvalue->addAll($sel_list);
	       if($propertyid && $valueid)
	       {
	       		$type_property->commit(); // 插入属性和属性值成功则提交
	       		
	       }else{
	       		$type->rollback();//不成功则回滚
	       		echo "<script type='text/javascript'>alert('添加类目失败，请重新添加'); window.location.href='/index.php/Admin/Type/index';</script>";
	       		
	       }

        }
        
	     //保存类目——规格
	     if(!empty($specids))
	     {
	     	$type_spec_list=array();
		     foreach($specids as $key=>$value)
		     {
		     	$type_spec_list[]=array('typeid'=>$typeid,'specid'=>$value);
		     }
	     	//批量添加 类目——规格
	     	$specid=M('type_spec')->addAll($type_spec_list);
	     }
	     //保存类目——品牌
	     if(!empty($brands))
	     {
	     		$brand_list=array();
	     		 foreach($brands as $key=>$value)
	     		 {
	     		 $brand_list[]=array('typeid'=>$typeid,'brandid'=>$value);
	     		 }
	     		//批量添加 类目——规格
	     		$bid=M('type_brand')->addAll($brand_list);
	     }

	     if($typeid || $propertyid || $specid  || $bid){
	     	 echo "<script type='text/javascript'>alert('添加类目成功'); window.location.href='/index.php/Admin/Type/index';</script>";
	     }    
	}	
	/**
	 *
	 * 返回已经确定子分类的类别属性，计算等级
	 *
	 */
	public function getListCat($data = array(),$level = 0) {
		$cats = array();
		!$data && $data = $this->getCats();
		if(!$data) return $cats;
		foreach($data as $key => $val) {
			$cats[$val['typeid']] = &$data[$key];
			$cats[$val['typeid']]['level'] = $level;
			if( isset( $val['children'] ) ) {
				$cats[$val['typeid']]['haschild'] = 1;
				$cats += $this->getListCat($val['children'],$level + 1);
				unset($data[$key]['children']);
			} 
		}
		return $cats;
	}
	
	/**
	 *
	 * 获取所有类别
	 *
	 */
	protected function getCats($return = 'tree') {
		static $retarr;
		if(isset($retarr[$return])) return $retarr[$return];

		$cats = M('type')->getField('typeid,typename,pid');
		if($return == 'tree')
		{			//返回数组
			$tree = array();

			foreach($cats as $cat)
			 {	//循环cat
				if(isset($cats[$cat['pid']])) 
				{//非第一级
					$cats[$cat['pid']]['children'][] = &$cats[$cat['typeid']];
				} else
				 {//第一级
					$tree[] = &$cats[$cat['typeid']];

				}
			}
			$retarr[$return] = $tree;
		} else if($return == 'source')
		 {//返回source
			$retarr[$return] = $cats;
		}
		return $retarr[$return];
	}
	/*
	 *ajax 删除类目下的扩展属性
	 *@param propertyid 扩展属性id
	 *return text
	 */
	public function ajaxDelpro(){
		$propertyid=I('post.propertyid','','strip_tags');
		$type_property=M('type_property');
		$type_propertyvalue=M('type_propertyvalue');
		$item_property=M('item_property');
		$type_property->startTrans();//开启事务
		$result['type_property']=$type_property->where('propertyid=%d',$propertyid)->delete();
		$result['type_propertyvalue']=$type_propertyvalue->where('propertyid=%d',$propertyid)->delete();
		$result['item_property']=$item_property->where('propertyid=%d',$propertyid)->delete();
		if($result['type_property'] && $result['type_propertyvalue'] && $result['item_property'] )
		{	//成功则提交
			$type_property->commit();
			echo 1;
		}else{
			//失败回滚
			$type_property->rollback();
			echo 0;
		}

	}
	/*
	 * 编辑商品属性ajax 获取规格值
	 * @param propertyid
	 * return json
	 */
	public function ajaxProval(){
		$propertyid=I('post.propertyid','','strip_tags');
		$result['proval']=M('type_propertyvalue')->where('propertyid=%d',$propertyid)->getField('valueid,propertyvalue');
		$result['propertyname']=M('type_property')->where('propertyid=%d',$propertyid)->getField('propertyname');
		if($result['proval'] && $result['propertyname']){
			$result['error']=0;
			echo json_encode($result);
		}else{
			$result['error']=1;
			echo json_encode($result);
		}
	}
	public function updateProper(){
		
		$propertyid=I('post.hiddpropid','','strip_tags');
		$data['propertyname']=I('post.name','','strip_tags');
		$value=I('post.proval','','strip_tags');
		$addval=I('post.addval','','strip_tags');
		$type_property=M('type_property');
		$typeid=$type_property->where('propertyid=%d',$propertyid)->getField('typeid');
		$type_propertyvalue=M('type_propertyvalue');
		if(!empty($addval)){
			foreach($addval as $key=>$v) {
				$tempdata['propertyvalue']=$v;
				$tempdata['propertyid']=$propertyid;
				$tempdata['typeid']=$typeid;
				$tempvalueid=$type_propertyvalue->add($tempdata);
				//$value[]=array($tempvalueid=>$value);
				array_push($value, array($tempvalueid=>$v));
			}
		}
		$data['selval']='';
		$newproval=array();
			foreach($value as $key=>$val)
			{
				foreach($val as $k=>$sv)
				{
					$data['selval'].=$sv.',';
					$newproval[$k]=array('propertyvalue'=>$sv);
				}
				
			}
		//更新属性
			$result=$type_property->where('propertyid=%d',$propertyid)->save($data);
			if($result !==false)
			{
				foreach($newproval as $key=>$value)
				{
					$res=$type_propertyvalue->where('valueid=%d',$key)->save($value);
				}
			}
			if($res===false){
				 echo "<script type='text/javascript'>alert('修改属性失败'); window.history.go(-1);window.location.reload();</script>";
			}else{
				 echo "<script type='text/javascript'>alert('修改属性成功'); window.history.go(-1);window.location.reload();</script>";
			}

	}
	//ajax 删除类目规格
		public function ajaxdelsel()
		{	
			$specid=I('post.specid','','strip_tags');
			$typeid=I('post.typeid','','strip_tags');
			$type_spec=M('type_spec');
			$result=$type_spec->where('specid=%d and typeid=%d',$specid,$typeid)->delete();
			//echo M()->getLastSql();
			if($result){
				echo true;
			}else{
				echo false;
			}

		}
	//上传图片
	public function uploadimg(){
			//保存商品图片
		$config['path']=C('Admin_IMG_PATH');
		$config['maxwidth']=C('LIST_MAX_WIDTH');
		$config['maxheight']=C('LIST_MAX_HEIGHT');
		 //判断是那个供应商上传的，重新定义图片路径
		 if(!file_exists($config['path']))
		 {	
		 	mkdir( $config['path'], 0777 , true );

		 }
		 $config['maxsize']=C('IMG_MAX_SIZE');
		 $img=imgUpload($config);
		 //上传出错
		 if(is_string($img)){
		 	return false;
		 }
		 $imginfo=$img['listimg'];
		 if(!empty($imginfo['savename']))
		 {
				$itemimg=substr(C('Admin_IMG_PATH'),1).$imginfo['savepath'].$imginfo['savename'];
		 }

		 return $itemimg;
	}

}